﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TeamWorkGH.Utils
{
    class UpAndDownloadFiles
    {
        public static Stream UploadStream(string filePath)
        {
            try
            {
                FileStream fileStream = File.OpenRead(filePath);
                return fileStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool DownloadStream(Stream stream, string filePath)
        {
            FileStream outStream = null;

            try
            {
                Console.WriteLine("Saving to File {0}", filePath);
                outStream = File.Open(filePath, FileMode.Create, FileAccess.Write);
                const int len = 4096;
                byte[] buffer = new byte[len];
                int count = 0;

                while ((count = stream.Read(buffer, 0, len)) > 0)
                {
                    Console.Write(".");
                    outStream.Write(buffer, 0, count);
                }

                Console.WriteLine();
                Console.WriteLine("File {0} saved", filePath);

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An exception was thrown while opening or writing to file {0}", filePath);
                Console.WriteLine("Exception: \n" + ex.Message);
                throw ex;
            }
            finally
            {
                if (outStream != null)
                {
                    outStream.Close();
                }
                stream.Close();
            }
        }
    }
}
